package com.zhentao.dataintegrity.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhentao.dataintegrity.domain.dto.IntegrityTaskDTO;
import com.zhentao.dataintegrity.service.IntegrityTaskService;
import com.zhentao.subscription.common.R;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/api/dataintegrity/tasks")
@CrossOrigin(origins = "*")
public class IntegrityTaskController {

    private static final Logger log = LoggerFactory.getLogger(IntegrityTaskController.class);

    @Autowired
    private IntegrityTaskService taskService;

    /**
     * 分页查询任务列表
     */
    @GetMapping
    public R<IPage<IntegrityTaskDTO>> getTaskPage(
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String taskTitle,
            @RequestParam(required = false) String taskStatus,
            @RequestParam(required = false) String triggerType) {
        try {
            IPage<IntegrityTaskDTO> page = taskService.getTaskPage(pageNo, pageSize, taskTitle, taskStatus, triggerType);
            return R.ok(page);
        } catch (Exception e) {
            log.error("查询任务列表失败", e);
            return R.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/{id}")
    public R<IntegrityTaskDTO> getTaskDetail(@PathVariable Long id) {
        try {
            IntegrityTaskDTO task = taskService.getTaskDetail(id);
            if (task == null) {
                return R.error("任务不存在");
            }
            return R.ok(task);
        } catch (Exception e) {
            log.error("获取任务详情失败: id={}", id, e);
            return R.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 创建任务
     */
    @PostMapping
    public R<Long> createTask(@Valid @RequestBody IntegrityTaskDTO taskDTO) {
        try {
            Long taskId = taskService.createTask(taskDTO);
            return R.ok(taskId);
        } catch (Exception e) {
            log.error("创建任务失败", e);
            return R.error("创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新任务
     */
    @PutMapping("/{id}")
    public R<Boolean> updateTask(@PathVariable Long id, @Valid @RequestBody IntegrityTaskDTO taskDTO) {
        try {
            taskDTO.setId(id);
            boolean success = taskService.updateTask(taskDTO);
            return success ? R.ok(true) : R.error("更新失败");
        } catch (Exception e) {
            log.error("更新任务失败: id={}", id, e);
            return R.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/{id}")
    public R<Boolean> deleteTask(@PathVariable Long id) {
        try {
            boolean success = taskService.deleteTask(id);
            return success ? R.ok(true) : R.error("删除失败");
        } catch (Exception e) {
            log.error("删除任务失败: id={}", id, e);
            return R.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 启用任务
     */
    @PostMapping("/{id}/enable")
    public R<Boolean> enableTask(@PathVariable Long id) {
        try {
            boolean success = taskService.enableTask(id);
            return success ? R.ok(true) : R.error("启用失败");
        } catch (Exception e) {
            log.error("启用任务失败: id={}", id, e);
            return R.error("启用失败: " + e.getMessage());
        }
    }

    /**
     * 禁用任务
     */
    @PostMapping("/{id}/disable")
    public R<Boolean> disableTask(@PathVariable Long id) {
        try {
            boolean success = taskService.disableTask(id);
            return success ? R.ok(true) : R.error("禁用失败");
        } catch (Exception e) {
            log.error("禁用任务失败: id={}", id, e);
            return R.error("禁用失败: " + e.getMessage());
        }
    }

    /**
     * 立即运行任务
     */
    @PostMapping("/{id}/run")
    public R<String> runTask(@PathVariable Long id,
                           @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
                           @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            String executionId = taskService.runTaskImmediately(id, startDate, endDate);
            return R.ok(executionId);
        } catch (Exception e) {
            log.error("立即运行任务失败: id={}", id, e);
            return R.error("运行失败: " + e.getMessage());
        }
    }

    /**
     * 取消执行
     */
    @PostMapping("/executions/{executionId}/cancel")
    public R<Boolean> cancelExecution(@PathVariable String executionId) {
        try {
            boolean success = taskService.cancelExecution(executionId);
            return success ? R.ok(true) : R.error("取消失败");
        } catch (Exception e) {
            log.error("取消执行失败: executionId={}", executionId, e);
            return R.error("取消失败: " + e.getMessage());
        }
    }

    /**
     * 获取数据类型选项
     */
    @GetMapping("/data-types")
    public R<List<IntegrityTaskDTO.DataTypeOption>> getDataTypeOptions() {
        try {
            List<IntegrityTaskDTO.DataTypeOption> options = taskService.getDataTypeOptions();
            return R.ok(options);
        } catch (Exception e) {
            log.error("获取数据类型选项失败", e);
            return R.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 检查任务标题是否存在
     */
    @GetMapping("/check-title")
    public R<Boolean> checkTaskTitleExists(@RequestParam String taskTitle,
                                         @RequestParam(required = false) Long excludeId) {
        try {
            boolean exists = taskService.checkTaskTitleExists(taskTitle, excludeId);
            return R.ok(exists);
        } catch (Exception e) {
            log.error("检查任务标题失败", e);
            return R.error("检查失败: " + e.getMessage());
        }
    }

    /**
     * 获取任务统计信息
     */
    @GetMapping("/statistics")
    public R<IntegrityTaskDTO> getTaskStatistics() {
        try {
            IntegrityTaskDTO statistics = taskService.getTaskStatistics();
            return R.ok(statistics);
        } catch (Exception e) {
            log.error("获取任务统计失败", e);
            return R.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取最近运行的任务
     */
    @GetMapping("/recent")
    public R<List<IntegrityTaskDTO>> getRecentTasks(@RequestParam(defaultValue = "5") int limit) {
        try {
            List<IntegrityTaskDTO> tasks = taskService.getRecentTasks(limit);
            return R.ok(tasks);
        } catch (Exception e) {
            log.error("获取最近任务失败", e);
            return R.error("获取失败: " + e.getMessage());
        }
    }
}
